package com.lcpress.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcpress.entity.Article;
import com.lcpress.entity.User;
import com.lcpress.service.impl.Admin_ArticleServiceImpl;
import com.lcpress.tools.ServletUtil;

@Controller
@RequestMapping(value = "/articlemg")
public class Admin_ArticleMgController {

	@Autowired
	Admin_ArticleServiceImpl articleService;

	@Value("${file.address}")
	private String UPLOADED_FOLDER;

	// 文章管理
	@RequestMapping("/articlelist")
	public String articlelistpage(HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");

		return "admin/admin_articlelist";
	}

	// 文章管理
	@RequestMapping("/addarticlepage")
	public String addarticlepage(HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");

		return "admin/admin_article_add";
	}

	// 添加文章操作
	@RequestMapping(value = "/addarticle_action", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addarticle_action(HttpServletRequest request) {

		String title = request.getParameter("title");
		String content = request.getParameter("content");

		HttpSession session = request.getSession();
		User user = (User) request.getSession().getAttribute("loginuser");

		Article article = new Article();
		article.setTitle(title);
		article.setContent(content);
		article.setCreatorid(user.getId());

		articleService.save(article);

		return ServletUtil.responseData(1, "文章保存成功！");
	}

	@RequestMapping(value = "/addarticlephoto_action", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addarticlephoto_action(@RequestParam("file") MultipartFile file) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (file.isEmpty()) {
			resultMap.put("errno", 1);
			resultMap.put("data", new ArrayList<String>());
			return resultMap;
		}

		File dir = new File(UPLOADED_FOLDER);
		if (!dir.exists()) {
			dir.mkdir();
		}

		// 通用唯一识别码
		UUID randomUUID = UUID.randomUUID();

		try {

			// Get the file and save it somewhere
			byte[] bytes = file.getBytes();

			String newName = String.valueOf(randomUUID)
					+ file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));

			Path path = Paths.get(UPLOADED_FOLDER + File.separatorChar + newName);
			Files.write(path, bytes);

			List<String> dataList = new ArrayList<String>();
			dataList.add("/uploadfile/" + newName);
			resultMap.put("errno", 0);
			resultMap.put("data", dataList);

		} catch (IOException e) {
			e.printStackTrace();
			resultMap.put("errno", 1);
			resultMap.put("data", new ArrayList<>());
		}

		return resultMap;
	}

	// 删除文章
	@RequestMapping(value = "/deletearticle_action", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deletearticle_action(HttpServletRequest request) {

		String title = request.getParameter("title");
		String content = request.getParameter("content");

		HttpSession session = request.getSession();
		User user = (User) request.getSession().getAttribute("loginuser");

		Article article = new Article();
		article.setTitle(title);
		article.setContent(content);
		article.setCreatorid(user.getId());

		articleService.save(article);

		return ServletUtil.responseData(1, "文章保存成功！");
	}

	// 获取我的文章列表
	@RequestMapping("/getmyarticlelist_action")
	@ResponseBody
	public Map<String, Object> getmyarticlelist_action(@RequestParam(value = "page", required = true) String page,
			@RequestParam(value = "limit", required = true) String limit, HttpServletRequest request) {

		HttpSession session = request.getSession();
		User user = (User) request.getSession().getAttribute("loginuser");

		Page<Article> page_info = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
		page_info.addOrder(OrderItem.asc("id"));
		Page<Article> userIPage = articleService.page(page_info,
				Wrappers.<Article>lambdaQuery().eq(Article::getCreatorid, user.getId()));

		var articles = userIPage.getRecords();
		var aritclenum = userIPage.getTotal();

		List<Object> dataList = new ArrayList<Object>();
		Map<String, Object> data;

		int count = 1;
		for (var article : articles) {
			data = new HashMap<String, Object>();

			data.put("id", count);
			data.put("title", article.getTitle());
			data.put("createdate", article.getCreatedate());
			data.put("updatedate", article.getUpdatedate());
			if (1 == article.getStatus()) {
				data.put("status", "公开");
			} else {
				data.put("status", "不公开");
			}

			dataList.add(data);
			count++;
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 0);
		resultMap.put("msg", "");
		resultMap.put("count", aritclenum);
		resultMap.put("data", dataList);

		return resultMap;
	}
	
	//文章预览
	@RequestMapping("/admin_article_preview/{atitle}/")
	public ModelAndView admin_article_preview(@PathVariable("atitle") String atitle,
													HttpServletResponse response) {
		
		Article article=articleService.getOne(Wrappers.<Article>lambdaQuery().eq(Article::getTitle, atitle));
		
		ModelAndView mView=new ModelAndView("admin/admin_article_preview");
		mView.addObject("article", article);
		
		return mView;
	}
	
	/**
	 * 以下为超级管理元功能部分
	 */

	// 超级用户-文章管理
	@RequestMapping("/super_article_list")
	public String super_article_list(HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");

		return "admin/super_article_list";
	}

	// 获取文章列表
	@RequestMapping("/getarticlelist")
	@ResponseBody
	public Map<String, Object> getarticlelist(@RequestParam(value = "page", required = true) String page,
			@RequestParam(value = "limit", required = true) String limit) {

		Page<Article> page_info = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
		page_info.addOrder(OrderItem.asc("id"));
		Page<Article> userIPage = articleService.page(page_info);
		// .selectPage(page, Wrappers.<User>lambdaQuery().eq(User::getAge,
		// 20).like(User::getName, "Jack"));

		var articles = userIPage.getRecords();
		var aritclenum = userIPage.getTotal();

		List<Object> dataList = new ArrayList<Object>();
		Map<String, Object> data;

		int count = 1;
		for (var article : articles) {
			data = new HashMap<String, Object>();

			data.put("id", count);
			data.put("title", article.getTitle());
			data.put("createdate", article.getCreatedate());
			data.put("updatedate", article.getUpdatedate());
			if (1 == article.getStatus()) {
				data.put("status", "公开");
			} else {
				data.put("status", "不公开");
			}

			dataList.add(data);
			count++;
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 0);
		resultMap.put("msg", "");
		resultMap.put("count", aritclenum);
		resultMap.put("data", dataList);

		return resultMap;
	}

}
